<script type="text/javascript">
    function submit() {
        $.postJSON("/invoice/save/", serializeData(), function(data) {
            if ('message' in data) {
                displayError(data.message.text);
            } else {
                changeContent(data.redirect);
            }
        }, "json");
    }

    function setPlusMinus() {
        // remove any existing + -
        $("div.plus").remove();
        $("div.minus").remove();

        // if only one line, just append a + to the right of that line
        // otherwise, append a + - to the right of each lines
        if ($("div.line").size() == 1) {
            $("div.line div.add-remove").append("<div class=\"plus\">&nbsp;</div>");
        } else {
            $("div.line div.add-remove").append("<div class=\"plus\">&nbsp;</div><div class=\"minus\">&nbsp;</div>");
        }

        $("div.plus").click(addLine);
        $("div.minus").click(function() {
            $(this).parent().parent().remove();
            setPlusMinus();
            updateTotal();
        });
        $("div#lines-block div.line div").removeClass("pointed-line");
        $("div#lines-block div.line:last div").addClass("pointed-line");

        $("input").change(function() {
            var quantity = $("[name=quantity]", $(this).parent().parent()).val();
            var price = $("[name=price]", $(this).parent().parent()).val();
            var vat = $("[name=vat]", $(this).parent().parent()).val();

            if (quantity > 0 && price > 0 && vat > 0) {
                var total = quantity * price * (1 + vat / 100);
                total = Math.round(total * 100) / 100;
                $("div.total", $(this).parent().parent()).html("<p>" + total + "&nbsp;&euro;</p>");
            }
            updateTotal();
        });
    }

    function updateTotal() {
        var total = 0;
        $("div.line").each(function() {
            var quantity = $("[name=quantity]", $(this)).val();
            var price = $("[name=price]", $(this)).val();
            var vat = $("[name=vat]", $(this)).val();

            if (quantity > 0 && price > 0 && vat > 0) {
                total += quantity * price * (1 + vat / 100);
            }
        })
        total = Math.round(total * 100) / 100;
        $("div.total-line div.total").html("<p>" + total + "&nbsp;&euro;</p>");
    }

    function addLine() {

        $("#lines-block form").append("" +
                "<div class=\"line\">" +
                "        <div class=\"description\">" +
                "            <input type=\"text\" size=\"60\" name=\"description\"/>" +
                "        </div>" +
                "        <div class=\"quantity\">" +
                "            <input type=\"text\" size=\"6\" name=\"quantity\"/>" +
                "        </div>" +
                "        <div class=\"price\">" +
                "            <input type=\"text\" size=\"6\" name=\"price\"/> &euro;" +
                "        </div>" +
                "        <div class=\"vat\">" +
                "            <input type=\"text\" size=\"6\" name=\"vat\"/> %" +
                "        </div>" +
                "        <div class=\"total\">" +
                "            <p>&nbsp;&euro;</p>" +
                "        </div>" +
                "        <div class=\"add-remove\">" +
                "            <div class=\"plus\">&nbsp;</div>" +
                "            <div class=\"minus\">&nbsp;</div>" +
                "        </div>" +
                "    </div>");
        setPlusMinus();
    }

    function serializeData() {
        var invoice = new Object();
        invoice.issueDate = Date.parse($("#date p").html());
        if ($("#client-name").val() != "") {
            var client = new Object();
            client.name = $("#client-name").val();
            client.street = $("#client div.data p.street").html();
            client.zip = $("#client div.data p.zipcity span.zip").html();
            client.city = $("#client div.data p.zipcity span.city").html();
            client.country = $("#client div.data p.country").html();
            client.vat = $("#client div.data p.vat").html();
            client.id = $("#client_id").html();
            invoice.client = client;
        } else {
            var contract = new Object();
            contract.reference = $("#contract-ref").val();
            invoice.contract = contract;
        }

        var lines = new Array();

        $.each($("div.line"), function(index, value) {
            var line = new Object();
            line.description = $('div.description input', $(this)).val();
            line.quantity = $('div.quantity input', $(this)).val();
            line.unit_price = $('div.price input', $(this)).val();
            line.vat = $('div.vat input', $(this)).val() / 100;
            lines.push(line);
        });

        invoice.lines = lines;

        return invoice;
    }

    activateMenuInvoice();
    activateSubMenuNew();

    {% if error_msg %}
        displayError({{ error_msg }})
    {% endif %}
</script>

<div id="newclient" title="New Client">
    <form>
        <div class="newclient_label"><label for="name">Name</label></div>
        <div class="newclient_data">
            <input type="text" name="name" id="name"/></div>
        <div class="newclient_label"><label for="street">Street</label></div>
        <div class="newclient_data"><input type="text" name="street" id="street" value=""/></div>
        <div class="newclient_label"><label for="zip">Zip</label></div>
        <div class="newclient_data"><input type="text" name="zip" id="zip" value=""/></div>
        <div class="newclient_label"><label for="city">City</label></div>
        <div class="newclient_data"><input type="text" name="city" id="city" value=""/></div>
        <div class="newclient_label"><label for="country">Country</label></div>
        <div class="newclient_data"><input type="text" name="country" id="country" value=""/></div>
        <div class="newclient_label"><label for="vat">VAT</label></div>
        <div class="newclient_data"><input type="text" name="vat" id="vat" value=""/></div>
    </form>
</div>

<div id="fromtimesheet" title="From Timesheet">
    <form>
        <div class="fromtimesheet_label"><label for="timesheet_selection">Timesheet</label></div>
        <div class="fromtimesheet_data">
            <select id="timesheet_selection">
                {% for timesheet_key,timesheet_value in availableTimesheets.items %}
                    <option value="{{ timesheet_key }}" selected="true">{{ timesheet_value }}</option>
                {% endfor %}
            </select>
        </div>
    </form>
</div>

<div id="invoice">
    <div id="invoice-header">
        <div id="invoice-data">
            <div class="label-value">
                <div class="label"><p>Facture</p></div>
                <div id="invoice-number" class="value"><p>xxxxxxxxxx</p></div>
            </div>
            <div class="label-value">
                <div class="label"><p>Date</p></div>
                <div id="date" class="value"><p>{{ today }}</p></div>
            </div>
        </div>
        <div id="client">
            <div class="label"><p>Client:</p></div>
            <input id="client-name" class="client-name"/>
            <a id="add_client" href="#"><img src="/static/img/add.png" alt="Add client"/></a>
            <a id="edit_address" href="#"><img src="/static/img/edit-32.png" alt="Edit Address"/></a>

            <div class="client-data">
                <p class="street">&nbsp;</p>

                <p class="zipcity"><span class="zip">&nbsp;</span>&nbsp;<span class="city">&nbsp;</span></p>

                <p class="country">&nbsp;</p>

                <p class="vat">&nbsp;</p>

                <div id="client_id">&nbsp;</div>
            </div>
        </div>
        {% if availableTimesheets|length > 0 %}
            <div id="timesheet-link">
                <a id="link-to-timesheet" href="#"><img src="/static/img/timesheet.png" alt="Generate from Timesheet"/></a>
            </div>
        {% endif %}
    </div>
    <div id="lines-block">
        <div id="lines-header">
            <div class="description pointed-line">
                <p>Description</p>
            </div>
            <div class="quantity pointed-line">
                <p>Quantity</p>
            </div>
            <div class="price pointed-line">
                <p>Price</p>
            </div>
            <div class="vat pointed-line">
                <p>VAT</p>
            </div>
            <div class="total pointed-line">
                <p>Total</p>
            </div>
            <div class="add-remove pointed-line"><p>&nbsp;</p></div>
        </div>
        <form>

        </form>
        <div class="total-line">
            <div class="description">
                <p>&nbsp;</p>
            </div>
            <div class="quantity">
                <p>&nbsp;</p>
            </div>
            <div class="price">
                <p>&nbsp;</p>
            </div>
            <div class="vat">
                <p>Total:</p>
            </div>
            <div class="total">
                <p>&nbsp; &euro;</p>
            </div>
        </div>
    </div>
</div>

<div id="actions">
    <button class="action" id="submit">Submit</button>
    <button class="action" id="cancel">Cancel</button>
</div>

<script type="text/javascript">
    $("#client-name").autocomplete({
        source: "/client/autocomplete/",
        minLength: 1,
        focus: function(event, ui) {
            $("#client-name").val(ui.item.name);
            return false;
        },
        select: function(event, ui) {
            $("#client .client-data p.street").html(ui.item.street);
            $("#client .client-data p.zipcity").html("<span class=\"zip\">" + ui.item.zip + "</span>&nbsp;<span class=\"city\">" + ui.item.city + "</span>");
            $("#client .client-data p.country").html(ui.item.country);
            $("#client .client-data p.vat").html(ui.item.vat);
            $("#client_id").html(ui.item.id);
            $("#edit_address").show();
            return false;
        }
    })
            .data("autocomplete")._renderItem = function(ul, item) {
        $("#client .client-data p.name").html("&nbsp;");
        $("#client .client-data p.street").html("&nbsp;");
        $("#client .client-data p.zipcity").html("&nbsp;");
        $("#client .client-data p.country").html("&nbsp;");
        $("#client .client-data p.vat").html("&nbsp;");
        $("#client_id").html("&nbsp;");

        return $("<li></li>")
                .data("item.autocomplete", item)
                .append("<a>" + item.name + "<br>" + item.zip + "&nbsp;&nbsp;" + item.city + "</a>")
                .appendTo(ul);
    };

    $("#submit").click(submit);

    $("#cancel").click(function() {
        changeContent("/invoice/view/");
    });

    activateSubMenuNew();

    $("#add_client").click(function() {
        $("#newclient").dialog({
            autoOpen: true,
            height: 310,
            width: 360,
            modal: true,
            buttons: {
                "Add": function() {
                    var client = new Object();
                    client.name = $("#newclient input[name=name]").val();
                    client.street = $("#newclient input[name=street]").val();
                    client.zip = $("#newclient input[name=zip]").val();
                    client.city = $("#newclient input[name=city]").val();
                    client.country = $("#newclient input[name=country]").val();
                    client.vat = $("#newclient input[name=vat]").val();

                    $.postJSON("/client/save/", client, function(data) {
                        if ('message' in data) {
                            displayError(data.message.text);
                        } else {
                            $("#client .client-data p.name").html(data.name);
                            $("#client .client-data p.street").html(data.street);
                            $("#client .client-data p.zipcity").html("<span class=\"zip\">" + data.zip + "</span>&nbsp;<span class=\"city\">" + data.city + "</span>");
                            $("#client .client-data p.country").html(data.country);
                            $("#client .client-data p.vat").html(data.vat);
                            $("#client_id").html(data.id);
                        }
                    }, "json")

                    $(this).dialog("close");
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        })
    });

    $("#edit_address").click(function() {
        $("#newclient input[name=name]").val($("#client #client-name").val());
        $("#newclient input[name=name]").attr('readonly', true);
        $("#newclient input[name=vat]").val($("#client .client-data p.vat").html());
        $("#newclient input[name=vat]").attr('readonly', true);
        $("#newclient").dialog({
            autoOpen: true,
            height: 310,
            width: 360,
            modal: true,
            buttons: {
                "Add": function() {
                    var address = new Object();
                    address.street = $("#newclient input[name=street]").val();
                    address.zip = $("#newclient input[name=zip]").val();
                    address.city = $("#newclient input[name=city]").val();
                    address.country = $("#newclient input[name=country]").val();

                    $.postJSON("/client/" + $("#client_id").html() + "/address/save/", address, function(data) {
                                if ('message' in data) {
                                    displayError(data.message.text);
                                } else {
                                    $("#client .client-data p.street").html(data.street);
                                    $("#client .client-data p.zipcity").html("<span class=\"zip\">" + data.zip + "</span>&nbsp;<span class=\"city\">" + data.city + "</span>");
                                    $("#client .client-data p.country").html(data.country);
                                }
                            }
                            ,
                            "json"
                    )

                    $(this).dialog("close");
                },
                "Cancel"
                        :
                        function() {
                            $(this).dialog("close");
                        }
            }
        })
    });

    $("#link-to-timesheet").click(function() {
        $("#fromtimesheet").dialog({
            autoOpen: true,
            height: 310,
            width: 360,
            modal: true,
            buttons: {
                "Add": function() {
                    $.getJSON("/timesheet/forInvoiceLine/" + $("#fromtimesheet option:selected").val(), null, function(data) {
                        if ('message' in data) {
                            displayError(data.message.text);
                        } else {
                            $('div.line div.description input').val(data.description);
                            $('div.line div.quantity input').val(data.quantity);
                            $('div.line div.price input').val(data.unit_price);
                            $('div.line div.vat input').val(data.vat);

                            var total = data.quantity * data.unit_price * (1 + data.vat / 100);
                            total = Math.round(total * 100) / 100;
                            $('div.total').html("<p>" + total + "&nbsp;&euro;</p>");
                            updateTotal();
                        }
                    }, "json")
                    $(this).dialog("close");
                },
                "Cancel": function() {
                    $(this).dialog("close");
                }
            }
        })
    })
    addLine();
    setPlusMinus();
</script>

